package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.MemberDiscount;
import factory.DaoFactory;

/**
 * Servlet implementation class AddDiscountServlet
 */
@WebServlet("/AddDiscountServlet")
public class AddDiscountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddDiscountServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.sendRedirect(request.getContextPath() + "/jsp/AddDiscount.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		float consumption = 0;
		float discount = 0;

		try {
			consumption = Float.parseFloat(request.getParameter("consumption"));
		} catch(NumberFormatException e) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=ConsumptionError");
			return;
		}
		
		if (consumption < 0) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=ConsumptionError");
			return;
		}

		try {
			discount = Float.parseFloat(request.getParameter("discount"));
		} catch(NumberFormatException e) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=DiscountError");
			return;
		}
		
		if (discount < 0 || discount > 1) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=DiscountError");
			return;
		}

		MemberDiscount memberDiscount = new MemberDiscount(consumption, discount);

		boolean success = DaoFactory.getDiscountDao().save(memberDiscount);
		if (success) {
			response.sendRedirect(request.getContextPath() + "/MemberDiscountManagementServlet");
		} else {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=DctDatabaseError");
		}

	}

}
